package api

import (
	"context"
	"delayed-task-hub/common"
	"delayed-task-hub/common/uniqueid"
	"encoding/json"
	"time"

	"delayed-task-hub/internal/svc"
	"delayed-task-hub/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type Create_taskLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreate_taskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Create_taskLogic {
	return &Create_taskLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *Create_taskLogic) Create_task(req *types.CreateTaskReq) (resp *types.CreateTaskResp, err error) {
	resp = &types.CreateTaskResp{}

	//index, _ := l.svcCtx.Redis.IncrbyCtx(l.ctx, fmt.Sprintf("%v:counter", req.ListName), 1)
	index := uniqueid.GenId()
	logx.Infof("index=%v", index)
	duration := time.Second * time.Duration(req.Delay)
	task := common.Package{
		ListName: req.ListName,
		PayLoad:  req.PayLoad,
		Index:    index,
	}

	taskJson, err := json.Marshal(task)
	if err != nil {
		resp.Code = 1
		resp.Msg = "格式错误"
		return
	} else {
		_, err := l.svcCtx.DqPusherClient.Delay(taskJson, duration)
		if err != nil {
			logx.Errorf("error from DqPusherClient Delay err : %v", err)
		}
	}
	return
}
